<template>
  <div class="mistake-list">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-select
            v-model="currentSubject"
            placeholder="选择科目"
            clearable
            @change="handleSubjectChange"
            style="width: 100%"
          >
            <el-option label="全部科目" :value="null" />
            <el-option
              v-for="subject in (subjects || [])"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索标题或内容"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 错题卡片列表 -->
    <div class="questions-container">
      <el-empty
        v-if="!loading && questions.length === 0"
        description="暂无错题"
      />

      <el-skeleton
        v-if="loading"
        :rows="3"
        animated
      />

      <div class="questions-grid">
        <div
          v-for="question in (questions || [])"
          :key="question.id"
          class="question-card"
          @click="handleShowDetail(question)"
        >
          <div class="question-header">
            <div class="question-meta">
              <el-tag size="small" type="primary">
                {{ getSubjectName(question.subjectId) }}
              </el-tag>
            </div>
            <div class="question-actions">
              <el-button
                v-if="isLoggedIn"
                size="small"
                type="danger"
                link
                @click.stop="handleDelete(question)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>

          <div class="question-content">
            <h3 class="question-title">
              {{ question.title || question.content.substring(0, 20) + (question.content.length > 20 ? '...' : '') }}
            </h3>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 图片预览 -->
    <ElImageViewer
      v-if="showImageViewer"
      :url-list="[currentImageUrl]"
      @close="showImageViewer = false"
    />

    <!-- 错题详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="错题详情"
      width="60%"
      :destroy-on-close="true"
    >
      <div v-if="currentQuestion" class="dialog-content">
        <!-- 科目和日期信息 -->
        <div class="dialog-header">
          <el-tag size="small" type="primary">
            {{ getSubjectName(currentQuestion.subjectId) }}
          </el-tag>
          <span class="question-date">
            {{ formatDate(currentQuestion.createdAt) }}
          </span>
        </div>

        <!-- 错题内容 -->
        <div class="dialog-body">
          <h3 v-if="currentQuestion.title" class="dialog-title">
            {{ currentQuestion.title }}
          </h3>
          <p class="dialog-text">{{ currentQuestion.content }}</p>

          <!-- 错题图片 -->
          <div v-if="currentQuestion.imageUrl" class="dialog-image">
            <img
              :src="getFullImageUrl(currentQuestion.imageUrl)"
              alt="错题图片"
              @click="previewImage(currentQuestion.imageUrl)"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button
            v-if="isLoggedIn"
            type="danger"
            @click="handleDeleteInDialog"
          >
            删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus'
import { Search, Refresh, Delete } from '@element-plus/icons-vue'
import { ElImageViewer } from 'element-plus'
import { useMistakeStore } from '@/store/mistake'
import { useAuthStore } from '@/store/auth'

const props = defineProps({
  isLoggedIn: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['edit', 'refresh'])

const mistakeStore = useMistakeStore()
const authStore = useAuthStore()

const searchKeyword = ref('')
const currentSubject = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const showImageViewer = ref(false)
const currentImageUrl = ref('')
const showDetailDialog = ref(false)
const currentQuestion = ref(null)

const subjects = computed(() => mistakeStore.subjects)
const questions = computed(() => mistakeStore.questions)
const total = computed(() => mistakeStore.total)
const loading = computed(() => mistakeStore.loading)

// 获取科目名称
const getSubjectName = (subjectId) => {
  return mistakeStore.getSubjectName(subjectId)
}

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleDateString('zh-CN')
}

// 加载错题列表
const loadQuestions = async () => {
  try {
    await mistakeStore.fetchQuestions({
      subjectId: currentSubject.value,
      keyword: searchKeyword.value,
      page: currentPage.value,
      size: pageSize.value
    })
  } catch (error) {
    console.error('加载错题列表失败:', error)
    ElMessage.error('加载错题列表失败')
  }
}

// 科目变化
const handleSubjectChange = () => {
  currentPage.value = 1
  mistakeStore.setCurrentSubject(currentSubject.value ? { id: currentSubject.value } : null)
  loadQuestions()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  mistakeStore.setSearchKeyword(searchKeyword.value)
  loadQuestions()
}

// 刷新
const handleRefresh = () => {
  loadQuestions()
  emit('refresh')
}

// 删除错题
const handleDelete = async (question) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条错题吗？${question.title ? `\n标题：${question.title}` : ''}`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await mistakeStore.deleteQuestion(question.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除错题失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  mistakeStore.setPageSize(newSize)
  loadQuestions()
}

// 页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  mistakeStore.setPage(newPage)
  loadQuestions()
}

// 获取完整的图片URL
const getFullImageUrl = (imageUrl) => {
  if (!imageUrl) return ''
  // 如果已经是完整URL则直接返回
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    return imageUrl
  }
  // 直接返回相对路径，vite proxy会处理代理
  return imageUrl
}

// 预览图片
const previewImage = (imageUrl) => {
  currentImageUrl.value = getFullImageUrl(imageUrl)
  showImageViewer.value = true
}

// 显示错题详情
const handleShowDetail = (question) => {
  currentQuestion.value = question
  showDetailDialog.value = true
}

// 在弹窗中删除错题
const handleDeleteInDialog = async () => {
  if (!currentQuestion.value) return

  try {
    await ElMessageBox.confirm(
      `确定要删除这条错题吗？${currentQuestion.value.title ? `\n标题：${currentQuestion.value.title}` : ''}`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await mistakeStore.deleteQuestion(currentQuestion.value.id)
    ElMessage.success('删除成功')
    showDetailDialog.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除错题失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 监听搜索输入，使用防抖
let searchTimer = null
watch(searchKeyword, () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 500)
})

// 初始化
onMounted(async () => {
  await mistakeStore.fetchSubjects()
  await loadQuestions()
})
</script>

<style scoped>
.mistake-list {
  padding: 20px;
}

.search-filter-section {
  margin-bottom: 20px;
}

.questions-container {
  min-height: 200px;
}

.questions-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.question-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  transition: box-shadow 0.3s;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  user-select: none;
}

.question-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.question-meta {
  display: flex;
  align-items: center;
}

.question-actions {
  display: flex;
  gap: 4px;
}

.question-content {
  flex: 1;
  display: flex;
  align-items: center;
}

.question-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  line-height: 1.3;
  text-align: center;
  word-break: break-all;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.question-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin: 0 0 12px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.question-image {
  margin-top: 12px;
}

.question-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.question-image img:hover {
  transform: scale(1.02);
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .questions-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .mistake-list {
    padding: 16px;
  }

  .questions-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .question-card {
    padding: 10px;
    min-height: 100px;
  }

  .question-title {
    font-size: 13px;
  }

  .search-filter-section .el-row {
    flex-direction: column;
    gap: 12px;
  }

  .search-filter-section .el-col {
    width: 100% !important;
  }

  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .question-actions {
    align-self: flex-end;
  }

  .pagination-section {
    text-align: center;
  }

  .pagination-section :deep(.el-pagination) {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .questions-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .question-card {
    padding: 8px;
    min-height: 80px;
  }

  .question-title {
    font-size: 12px;
  }
}

/* 弹窗样式 */
.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.dialog-body {
  margin-top: 16px;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.dialog-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0 0 16px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.dialog-image {
  margin-top: 16px;
  text-align: center;
}

.dialog-image img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-image img:hover {
  transform: scale(1.02);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}
</style>